package com.example.spirngbootbase.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.spirngbootbase.bean.LoginUser;
import com.example.spirngbootbase.bean.SysUser;
import com.example.spirngbootbase.mapper.MenuMapper;
import com.example.spirngbootbase.mapper.SysUserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName UserDetailsServiceImpl
 * @Description TODO
 * @Author mujiechen
 * @Date 2022/7/28
 */
@Service

public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    SysUserMapper sysUserMapper;

    @Resource
    MenuMapper menuMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName,username);
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        //如果查询不到数据就通过抛出异常来给出提示
        if(Objects.isNull(sysUser)){
            throw new RuntimeException("用户名或密码错误");
        }
        //TODO 根据用户查询权限信息 添加到LoginUser中
        List<String> permissionKeyList =  menuMapper.selectPermsByUserId(sysUser.getId());
        //封装成UserDetails对象返回
        return new LoginUser(sysUser,permissionKeyList);
    }
}
